# coding:utf-8
"""
@author: jing
@contact: 529548204@qq.com
@file: requestsTearDown.py
@time: 2022/5/11 13:28
"""
import logging

from common.basePage import apisend
from common.checkResult import asserting
from util.tools.iniHeaders import iniheaders
from util.tools.datasTypeChange import strhandleurl, valuehandle
from util.tools.log import Log
import jsonpath
import allure

from util.tools.readYamlFile import readredisdata

Log()


def caseteardown(casedata, caseres, headerdata=None):
    """
    使用场景: 新增数据A之后一系列用例执行完需要后置来还原数据形成业务闭环.
    datatype 有3种类型 param json 和urlparam
    dataname为后置关联的参数中参数名称
    path为当前请求返回结果的jsonpath 根据path的值更换后置处理参数值
    如果不需要后置处理 teardown 置空即可
    :param casedata: 测试数据
    :param caseres: 当前用例返回结果
    :param headerdata: 请求头数据
    :return:
    """
    teardowndata = casedata["teardown"]
    if teardowndata:
        for req in teardowndata:
            case = readredisdata(req["tdName"])
            tdcase = case["case"][req["tdNum"] - 1]
            try:
                with allure.step("执行后置接口"):
                    if case["token"]:
                        # 处理请求头
                        tdcase["headers"] = iniheaders(tdcase["headers"])
                        tdcase["headers"][case["token"]] = headerdata
                        for tddata in req["tddata"]:
                            # 循环处理后置请求参数
                            value = jsonpath.jsonpath(caseres, tddata["path"])[0]
                            if tddata["datatype"] == "param":
                                # 后置参数为param类型时
                                middata = valuehandle(tdcase["data"]["param"])
                                # 为了方便处理 转化为字典 然后更换值之后再转化为param字符串
                                middata[tddata['dataname']] = value
                                tdcase["data"]["param"] = strhandleurl(middata)
                            elif tddata["datatype"] == "json":
                                # 后置参数为json类型时
                                if not isinstance(tdcase["data"]["param"], dict):
                                    raise TypeError("['data']['param']格式错误")
                                tdcase["data"]["param"][tddata['dataname']] = value
                            elif tddata["datatype"] == "urlparam":
                                # 后置参数为url路径类型时
                                tdcase["data"]["urlparam"] = {
                                    tddata['dataname']: value
                                }
                        # 执行后置请求
                        res, code, restime = apisend(http=tdcase["http"], address=tdcase["address"],
                                                     method=tdcase["method"], headers=tdcase["headers"],
                                                     data=tdcase["data"],
                                                     caches=tdcase["cache"], host=tdcase["host"])
                        asserting(hope_res=tdcase["assert"], real_res=res, re_time=restime, re_code=code)
                        logging.info(f"成功执行后置接口:{tdcase['info']}")

            except Exception as e:
                logging.error(f"执行后置接口:{tdcase['info']}错误,{e}")
                raise
